package org.vt.eldercare.ui;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset;
import org.vt.eldercare.data.DataPoint;

public class ChartCollection {
	
	private JFreeChart accelChart;
	private TimeSeries accelerometerX;
	private TimeSeries accelerometerY;
	private TimeSeries accelerometerZ;
	private JFreeChart gyroChart;
	private TimeSeries gyroX;
	private TimeSeries gyroY;
	private TimeSeries gyroZ;
	private static final int MAX_ITEM_COUNT = 72000; // 1 hour of data at 20
														// samples/sec
	
	public ChartCollection(){
		accelerometerX = new TimeSeries("X Axis");
		accelerometerY = new TimeSeries("Y Axis");
		accelerometerZ = new TimeSeries("Z Axis");
		gyroX = new TimeSeries("X Axis");
		gyroY = new TimeSeries("Y Axis");
		gyroZ = new TimeSeries("Z Axis");
		accelerometerX.setMaximumItemCount(MAX_ITEM_COUNT);
		accelerometerY.setMaximumItemCount(MAX_ITEM_COUNT);
		accelerometerZ.setMaximumItemCount(MAX_ITEM_COUNT);
		gyroX.setMaximumItemCount(MAX_ITEM_COUNT);
		gyroY.setMaximumItemCount(MAX_ITEM_COUNT);
		gyroZ.setMaximumItemCount(MAX_ITEM_COUNT);
		TimeSeriesCollection collection = new TimeSeriesCollection();
		collection.addSeries(accelerometerX);
		collection.addSeries(accelerometerY);
		collection.addSeries(accelerometerZ);
		accelChart = createChart(collection, "Accelerometer Data", "Time",
				"Accleration (G)");
		collection = new TimeSeriesCollection();
		collection.addSeries(gyroX);
		collection.addSeries(gyroY);
		collection.addSeries(gyroZ);
		gyroChart = createChart(collection, "Gyro Data", "Time", "Value");
	}
	
	/**
	 * Creates a sample chart.
	 * 
	 * @param dataset
	 *            the dataset.
	 * 
	 * @return A sample chart.
	 */
	private JFreeChart createChart(final XYDataset dataset, String title,
			String xLabel, String yLabel) {
		final JFreeChart result = ChartFactory.createTimeSeriesChart(title,
				xLabel, yLabel, dataset, true, true, false);
		final XYPlot plot = result.getXYPlot();
		ValueAxis axis = plot.getDomainAxis();
		axis.setAutoRange(true);
		axis.setFixedAutoRange(60000.0); // 60 seconds
		axis = plot.getRangeAxis();
		axis.setAutoRange(true);
		return result;
	}
	
	public void addDataSet(DataPoint point){
		accelerometerX.add(point.getTime(), point.getAccelX());
		accelerometerY.add(point.getTime(), point.getAccelY());
		accelerometerZ.add(point.getTime(), point.getAccelZ());
		gyroX.add(point.getTime(), point.getGyroX());
		gyroY.add(point.getTime(), point.getGyroY());
		gyroZ.add(point.getTime(), point.getGyroZ());
	}

	public JFreeChart getAccelChart() {
		return accelChart;
	}

	public JFreeChart getGyroChart() {
		return gyroChart;
	}

}
